package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private DishFlavorService dishFlavorService;


    public void saveWithFlavorTwo(DishDto dish) {

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != dish.getName(),Dish::getName,dish.getName());
        Integer count = dishMapper.selectCount(wrapper);
        if (count > 0) {
            throw new CustomException("已经存在["+dish.getName()+"]数据");
        }
        int i = dishMapper.insert(dish);
        if (i > 0)log.info("新增菜品数据成功{}",dish);
        // 根据数据库name唯一约束查询出新增的菜品信息 获取它的id值
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(!"".equals(dish.getName()),Dish::getName,dish.getName() );
        Dish newDish = dishMapper.selectOne(qw);
        Long dishId = newDish.getId();

        List<DishFlavor> dishFlavorList = dish.getFlavors();
        for (DishFlavor flavor : dishFlavorList) {
            DishFlavor dishFlavor = new DishFlavor();
            dishFlavor.setDishId(dishId);
            dishFlavor.setName(flavor.getName());
            dishFlavor.setValue(flavor.getValue());
            int insert = dishFlavorMapper.insert(dishFlavor);
            if (insert > 0 ) log.info("新增菜品口味成功!");
        }

    }


    @Override
    public void saveWithFlavor(DishDto dishDto) {

        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //保存完成后生成的id,createTime,updateTime,createUser,updateUser 自动注入到对象之中
        Long dishId = dishDto.getId();//菜品id
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {

        Dish dish = dishMapper.selectById(id);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != dish.getId(),DishFlavor::getDishId,dish.getId());
        // DishFlavor flavor = dishFlavorMapper.selectOne(wrapper);
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);
        DishDto dishDto = new DishDto();
        dishDto.setFlavors(flavors);
        BeanUtils.copyProperties(dish,dishDto);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(qw);       //删除能够匹配到的菜品关联口味

        List<DishFlavor> flavors = dishDto.getFlavors();

        List<DishFlavor> list = flavors.stream().map((item) -> {
            //上面的删除是逻辑删除 此时添加的id会重复
            item.setId(IdWorker.getId());    //进行随机id的设置 覆盖原有id
            item.setDishId(dishDto.getId());       //为新增进入的菜品口味关联菜品id
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(list);

    }

    @Override
    public void batchDeletion(Long[] ids) {

        if (null == ids && 0 == ids.length) {
            throw new CustomException("删除菜品id为空.");
        }

        for (int i = 0; i < ids.length; i++) {
            //在删除之前对所删除菜品id进行判断 其中有存在正在起售的菜品则中断删除操作
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(Dish::getStatus,1);
            qw.eq(Dish::getId,ids[i]);
            int count = this.count(qw);
            if (count > 0) {            //若查询出的数据数量大于0 说明存在正在售卖的菜品 抛出异常
                throw new CustomException("无法执行删除,存在正在售卖的菜品");
            }
        }
        this.removeByIds(Arrays.asList(ids));    //理想情况是执行逻辑删除
    }

    @Override
    public void batchOperation(Integer state, List<Long> ids) {

        if (null == ids && 0 == ids.size()) throw new CustomException("更改数据的id值不能为空.");
        this.update(new LambdaUpdateWrapper<Dish>().set(Dish::getStatus,state).in(Dish::getId,ids));
    }
}
